'''
Author: Pabin <pabin_pluto@foxmail.com>
Date: 2023-10-25 16:45:58
LastEditors: Pabin <pabin_pluto@foxmail.com>
LastEditTime: 2023-10-25 16:46:16
FilePath: \eagain-base\RaspiCode\main.py
Description: 

Copyright (c) 2023 by Pabin, All Rights Reserved. 
'''
import cv2 as cv
import numpy as np
import EView as ev
import serial
import time


# * 创建工作模式变量
model = '0'
# * 创建一个摄像头捕获对象
cap = cv.VideoCapture(0)

if not cap.isOpened():
    print("Cannot open camera")
    exit() 

# * 创建一个坐标捕捉对象
PointCap = ev.Pointcapture()
# * 创建一个外设控制对象
Peri = ev.Peripheral()
# 8 初始化串口
Peri.UartInit(115200)

while True:
    # 逐帧捕获
    ret, frame = cap.read()
    # 如果正确读取帧，ret为True
    if not ret:
        print("Can't receive frame (stream end?). Exiting ...")
        break
    frame = frame[15:450,120:560]
    cv.imshow('frame',frame)
    # 获取串口
    uartdata = Peri.getUartData()
    if  uartdata !=None:
        model = uartdata
    if model == '0' :     # * 获取红斑坐标点
        redpos,reddrawimg = PointCap.getReddotPos(frame, 30, 32, 0, 10, 230, 255, display=True)
        Peri.sendUartData(f"reddotPos: {redpos}")
        cv.putText(reddrawimg, str(redpos), (100,100), cv.FONT_HERSHEY_SIMPLEX, 1, (0,0,255), 2, cv.LINE_AA)
        cv.imshow('reddrawimg',reddrawimg)
#     elif model == '1' :   # * 获取绿斑坐标点
#         greenpos,greendrawimg = PointCap.getGreendotPos(frame, 49, 106, 5, 31, 255, 255, display=True)
#         print("greendotPos:",greenpos)
#         Peri.Uart.write(f"greendotPos: {greenpos}".encode('utf-8'))
#         cv.putText(greendrawimg, str(greenpos), (100,100), cv.FONT_HERSHEY_SIMPLEX, 1, (0,255,0), 2, cv.LINE_AA)
#         cv.imshow('greendrawimg',greendrawimg)
#     elif model == '2' :   # * 获取红斑坐标点和黑色路线
#         redpos,reddrawimg = PointCap.getReddotPos(frame, 30, 32, 0, 10, 230, 255, display=True)
#         cv.imshow('reddrawimg',reddrawimg)
#         route_list, skeleton = PointCap.getBlackRoute(imggg, optimize=True)
#         for each in route_list:
#             print("target: ",each," ","current: ",redpos) #!暂代传输函数
#             Peri.Uart.write(f"target: {each} current: {redpos}".encode('utf-8'))
#             count = Peri.Uart.inWaiting()
#             if count != 0:
#                 model =  Peri.Uart.read(count).decode('utf-8') 
#             if model!='2' :
#                 break    
#     elif model == '3':    # * 获取红斑坐标点和黑色矩形框路线
#             redpos,reddrawimg = PointCap.getReddotPos(frame, 30, 32, 0, 10, 230, 255, display=True)
#             route_list,rect_center = PointCap.getBlackRectRoute(frame,7)
#             for each in route_list:
#                 cv.circle(frame,tuple(each), 1, (0,0,255), -1)
#                 cv.imshow('route',frame)
            
#     else:
#         pass 
    if cv.waitKey(1) == ord('q'):
            break

# # 完成所有操作后，释放捕获器
# cap.release()
# cv.destroyAllWindows()